package com.binyong.redis.service.impl;

import com.binyong.constant.RedisConstant;
import com.binyong.redis.service.RedisSubscribeService;
import com.binyong.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 客户总线监听方法
 * @author binyong
 *
 */
@Component
@Slf4j
public class TestSubscribeServiceImpl extends MessageListenerAdapter implements RedisSubscribeService {
	
	@Override
	public void onMessage(Message message, byte[] pattern) {
		if (Objects.isNull(message)) {
            log.error("消息为空");
            return;
        }

		//消息体中可以指定具体的业务内容，按照要求发送给不同的人。
		String channel = new String(message.getChannel());
        String data = new String(message.getBody());
        if(StringUtils.equals(channel, RedisConstant.msg_queue)) {
			try {
				//发送给所有客户
				WebSocketServer.sendInfoAll(data);
			} catch (Exception e) {
				log.error("客户总线监听异常",e);
			}
        }
        log.info("客户总线订阅频道：{}消息：{}", channel, data);
	}

}
